package org.hongbo.springbootebsapi.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.hongbo.springbootebsapi.annotations.AllowRespInfoNull;
import org.hongbo.springbootebsapi.entity.CheckResult;
import org.hongbo.springbootebsapi.enums.ResultCode;
import org.hongbo.springbootebsapi.exceptions.BusinessException;
import org.hongbo.springbootebsapi.jwt.Audience;
import org.hongbo.springbootebsapi.jwt.JwtTokenUtil;
import org.hongbo.springbootebsapi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class TokenValidInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    Audience audience;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            String authHeader = request.getHeader(audience.getAuthorization());
            //签名验证不存在
            if (StringUtil.isEmpty(authHeader)) {
                throw new BusinessException(ResultCode.JWT_TOKEN_NOT_EXISTS);
            }
            if (StringUtil.isNotEmpty(authHeader)  && authHeader.startsWith(audience.getTokenHead())) {
                final String authToken = authHeader.substring(audience.getTokenHead().length()); // The part after "Bearer "

                CheckResult checkResult = jwtTokenUtil.validateJWT(authToken);
                if (!checkResult.isSuccess()) {
                    // 签名验证不通过
                    if (checkResult.getErrCode() == ResultCode.JWT_ERRCODE_FAIL.code()) {
                        throw new BusinessException(ResultCode.JWT_ERRCODE_FAIL);
                    }
                    // 签名过期，返回过期提示码
                    if (checkResult.getErrCode() == ResultCode.JWT_ERRCODE_EXPIRE.code()) {
                        throw new BusinessException(ResultCode.JWT_ERRCODE_EXPIRE);
                    }
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // nothing to do
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // nothing to do
    }
}
